const express=require('express');
const url=require('url');

let router=express.Router();
module.exports=router;


router.get('/',(req,res)=>{
	let {page}=req.query;
	page=parseInt(page);

	if(isNaN(page)||page<1){
		page=1;
	}
	let page_size=3;
	let page_start=(page-1)*page_size;

	let sql=`SELECT ID,title,sub_title,position_main,position_second,ave_price,main_img_path,area_min,area_max,property_types FROM house_table LIMIT ${page_start},${page_size}`
	req.db.query(sql,(err,data_house)=>{
		if(err){
			res.sendStatus(500);
		}else{
			req.db.query(`SELECT COUNT(*) AS c FROM house_table`,(err,data)=>{
				if(err){
			res.sendStatus(500);
		}else{
			res.render('list',{
				list_data:data_house,
				page_count:Math.ceil(data[0].c/page_size),
				cur_page:page,
			})
		}
			})
			
		}
	})
	
});

router.get('/detail/:id/',(req,res)=>{
	let {id}=req.params;

	req.db.query(`SELECT * FROM house_table WHERE ID='${id}'`,(err,data)=>{
		if(err){
			res.showError(500);
			console.log(err)
		}else{
			res.render('detail',{data:data[0]})
		}
	})
});

//放外部直接盗取资源，避免加重服务器负担
router.get('/static_img/:img_path',(req,res)=>{
	let {img_path}=req.params;

	let obj =url.parse(req.headers['referer']);
	if(obj.host!='localhost:8080'){
		res.sendStatus(500);
	}else{
		res.sendFile(`${req.cwd}\\upload\\${img_path}`);
	}
	})